package com.linewow.xhyy.nihaonew.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;

import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.squareup.picasso.Transformation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.Random;


/**
 * Created by LXR on 2016/5/16.
 */
public class CommonUtil {
    public static String getVersion(Context context)//获取版本号
    {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return context.getString(R.string.unknown_version_name);
        }
    }

    public static int getVersionCode(Context context)//获取版本号(内部识别号)
    {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }

    public static int getWindowWid(Activity act) {
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        act.getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        return mDisplayMetrics.widthPixels;
    }

    public static int getWindowHei(Activity act) {
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        act.getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        return mDisplayMetrics.heightPixels;
    }

    //需要初始化创建文件夹
    public static String getPhotoPath(Context ctx) {
        String state = Environment.getExternalStorageState();
        String path = state.equals(Environment.MEDIA_MOUNTED) ? (Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + ctx.getResources().getString(R.string.app_name_english) + "/") :
                "" + ctx.getCacheDir().getAbsolutePath() + "/NiHao/";
        return path;
    }

    public static int dp2px(Context context, int dpValue) {
        return (int) (dpValue * context.getResources().getDisplayMetrics().density);
    }


    public static Transformation getTransformation(final Context context) {

        Transformation transformation = new Transformation() {

            @Override
            public Bitmap transform(Bitmap source) {

                int targetWidth = CommonUtil.getWindowWid((Activity) context);
                Log.e("MainActivity", "source.getHeight()=" + source.getHeight() + ",source.getWidth()=" + source.getWidth() + ",targetWidth=" + targetWidth);

                if (source.getWidth() == 0) {
                    return source;
                }
                //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
                double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
                int targetHeight = (int) (targetWidth * aspectRatio);
                if (targetHeight != 0 && targetWidth != 0) {
                    Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
                    if (result != source) {
                        // Same bitmap is returned if sizes are the same
                        source.recycle();
                    }
                    return result;
                } else {
                    return source;
                }

            }

            @Override
            public String key() {
                return "transformation" + " desiredWidth";
            }
        };

        return transformation;
    }






    public static String getLength(String string) {   //使用此方法可以直接在后台获取音频文件的播放时间，而不会真的播放音频
        MediaPlayer player = new MediaPlayer();  //首先你先定义一个mediaplayer
        try {
            player.setDataSource(string);  //String是指音频文件的路径
            player.prepare();        //这个是mediaplayer的播放准备 缓冲

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {//监听准备

            @Override
            public void onPrepared(MediaPlayer player) {
                int size = player.getDuration();
                String timelong = size / 1000 + "";

            }
        });
        double size = player.getDuration();//得到音频的时间
        String timelong1 = (int) Math.ceil((size / 1000)) + "";//转换为秒 单位为''
        player.stop();//暂停播放
        player.release();//释放资源
        return timelong1;  //返回音频时间

// TODO Auto-generated method stub
    }

    public static String getNiHaoToken() {
        String token = NiHaoApp.token;
        String token1 = null;
        try {
            token1 = URLEncoder.encode(token, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return token1;
    }

    public static String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public static String getMD5(String info) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();

            StringBuffer strBuf = new StringBuffer();
            for (int i = 0; i < encryption.length; i++) {
                if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                    strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                } else {
                    strBuf.append(Integer.toHexString(0xff & encryption[i]));
                }
            }

            return strBuf.toString();
        } catch (NoSuchAlgorithmException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    public static int getSaltInt() {
        Random random = new Random();
        return random.nextInt(1000);
    }

    public static Locale languageLocale(Context context){
        Resources resources=context.getResources();
        Configuration config = resources.getConfiguration();
        return  config.locale;
    }

    public static  boolean ChineseLocale(Context context){
        Locale locale=languageLocale(context);
        return (locale.equals(Locale.TAIWAN)||locale.equals(Locale.CHINA)||locale.equals(Locale.CHINESE)||locale.equals(Locale.TRADITIONAL_CHINESE)||locale.equals(Locale.SIMPLIFIED_CHINESE));
    }

}
